package blms.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;

/**
 * This class handles date format for BLMS system. It follows the pattern used
 * in internationalization code like {@link ResourceBundle}. This pattern,
 * usually provides a single access point to the system (implemented by static
 * final references, singletons etc).
 * 
 * @author Thiago Emmanuel Pereira da Cunha Silva, thiago.manel@gmail.com
 */
public class LocalizedDataFormat {

	private static DateFormat dateFormat;

	static {
		LocalizedDataFormat.setDateFormat("dd/MM/yyyy");
	}

	public static void setDateFormat(final String format) {
		if (ValidatorUtil.isBlankOrNull(format)) {
			throw new RuntimeException("Unknown date format");
		}
		try {
			String dFormat = format;
			dFormat = dFormat.replaceAll("D", "d");
			dFormat = dFormat.replaceAll("m", "M");
			dFormat = dFormat.replaceAll("Y", "y");
			final DateFormat sdf = new SimpleDateFormat(format);
			sdf.setLenient(false);
			dateFormat = sdf;

		} catch (final Exception e) {
			throw new RuntimeException("Unknown date format");
		}
	}

	public static Date parse(final String date) throws ParseException {
		return dateFormat.parse(date);
	}

	public static String formatDate(final Date date) {
		return dateFormat.format(date);
	}

}